import pygame
from pygame.locals import *
import random

color_white = pygame.Color(255,255,255)
color_red = pygame.Color(255,0,0)
color_black = pygame.Color(0,0,0)

def main():
    # 初始化
    pygame.init()
    fpsClock = pygame.time.Clock()

    screen = pygame.display.set_mode((600,460))

    snake_head = [100,100]
    snake_body = [[100,100]]
    food = [300,300]
    food_num = 1
    direction = 'right'
    score = 0

    while True:
        pygame.display.update()

        # 获取事件，比如按键等
        for event in pygame.event.get():
            # 判断是否是点击了退出按钮
            if event.type == QUIT:
                exit()
            # 判断是否是按下了键
            elif event.type == KEYDOWN:
                # 检测按键是否是a或者left
                if event.key == K_a or event.key == K_LEFT:
                    direction = 'left'
                # 检测按键是否是d或者right
                elif event.key == K_d or event.key == K_RIGHT:
                    direction = 'right'
                elif event.key == K_w or event.key == K_UP:
                    direction = 'up'
                elif event.key == K_s or event.key == K_DOWN:
                    direction = 'down'

        if direction == 'right':
            snake_head[0] += 20
        if direction == 'left':
            snake_head[0] -= 20
        if direction == 'up':
            snake_head[1] -= 20
        if direction == 'down':
            snake_head[1] += 20

        snake_body.insert(0,list(snake_head))
        # 判断是否吃到食物
        if snake_head[0] == food[0] and snake_head[1] == food[1]:
            food_num = 0
        else:
            snake_body.pop()
        # 如果吃到了食物 随机生成食物
        if food_num == 0:
            x = random.randrange(1,30)
            y = random.randrange(1,23)
            food = [int(x*20),int(y*20)]
            food_num = 1
            score += 1

        screen.fill(color_black)
        # 绘制显示层
        for snake in snake_body:
            pygame.draw.rect(screen,color_white,Rect(snake[0],snake[1],20,20))
            pygame.draw.rect(screen,color_red,Rect(food[0], food[1],20,20))
        # 刷新显示层
        pygame.display.flip()

        # 判断是否死亡
        if snake_head[0] > 580 or snake_head[0] < 0:
            print('gameover')
            print('分数：%s'%score)
            exit()
        if snake_head[1] > 440 or snake_head[1] < 0:
            print('gameover')
            print('分数：%s'%score)
            exit()
        for snakeBody in snake_body[1:]:
            if snake_head[0] == snakeBody[0] and snake_head[1] == snakeBody[1]:
                print('gameover')
                print('分数：%s' % score)
                exit()

        fpsClock.tick(10)

if __name__ == '__main__':
    main()